'''提供搜索的代码
Class Get() -> 搜索类
'''

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
from lxml import *
import eyed3
from eyed3.id3.frames import ImageFrame
import time,requests,os
import base64
 
#将内容转为base64格式内容
def convertToBase64(info):
    try:
        tmpBytes=info.encode()
        tmpBase64=base64.b64encode(tmpBytes)
        return tmpBase64
    except Exception as e:
        print('异常：',e)
def clear_directory(path,tree=0):
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if os.path.isfile(file_path):
            print("del:",file_path)
            os.remove(file_path)
#将base64格式内容转为正常信息
def convertTostring(base64Info):
    try:
        tmpBytes=base64.b64decode(base64Info)
        tmpStr=tmpBytes.decode()
        return tmpStr
    except Exception as e:
        print('异常：',e)
class MyService(Service):
    def __init__(self, executable_path: str,
                 port: int = 0, service_args=None,
                 log_path: str = None, env: dict = None):
        super(Service, self).__init__(
            executable_path,
            port,
            service_args,
            log_path,
            env,
            "Please see https://chromedriver.chromium.org/home")
        self.creation_flags = 134217728

class Get():
    '''启动浏览器搜索音乐 -> Class\n
    self.get(input) -> 以关键词:input 搜索
    '''
    def __init__(self):
        self.dz="C:\\Users\\"+os.getlogin()+"\\.musics"
        self.options = webdriver.ChromeOptions()
        self.options.add_argument('--headless')
        self.options.add_experimental_option('excludeSwitches', ['enable-logging'])
        self.session = webdriver.Chrome(options=self.options,service=MyService(ChromeDriverManager().install()))
        if not os.path.exists(self.dz+"\\tmp"):
            os.makedirs(self.dz+"\\tmp")
    def mp3_bit(mp3Path):
        mp3Info = eyed3.mp3.Mp3AudioFile(mp3Path)
        # print(mp3Info.info.bit_rate[1])
        return (mp3Info.info.bit_rate[1],mp3Info.info.time_secs)
    def exits(self):
        self.session.quit()
    def get(self,search):
        if search=="open tmp":
            os.system("start "+self.dz+"\\tmp")
            return
        if search=="clear tmp":
            print("正在清空缓存")
            clear_directory(self.dz+"\\tmp")
            return
        ok=True
        gets=0
        url="https://www.qqwtt.com/?name="+search+"&type=netease"
        print("正在搜索")
        self.session.get(url)
        while ok:
            html = self.session.execute_script('return document.documentElement.outerHTML')
            print("正在分析音乐地址")
            soup = BeautifulSoup(html,"lxml")
            tmp=[]
            for i in soup.find_all('a'):
                if i.get('id')=="j-src-btn" and i.get('href')!=None:
                    link=i.get('href')
                    break
            try:
                name=link.split("=")[1]
                ok=False
                print("正在获取音乐地址")
                print("正在获取音乐歌词")
                links=soup.find(id="j-lrc-btn").get("href")
                print("正在获取歌曲名称")
                title=soup.find(class_="aplayer-title").text
                print("正在获取歌曲歌手")
                people=soup.find(class_="aplayer-author").text[3:]
                print("正在获取封面")
                fmlink=soup.find("div",class_="aplayer-pic").get("style").replace("background-image: url('","").replace("?param=300x300');","")
                # print(fmlink)
                print("\n有关的歌曲:")
                ge=soup.find("ol").find_all("li")
                for i in ge:
                    for j in i.find_all("span"):
                        print(j.text,end=" ")
                    print()
                print()
            except:
                gets+=1
                if gets>10:
                    print("搜索失败，没有和关键词有关的歌")
                    return
                time.sleep(0.5)
        self.exits()
        musics=[]
        for music in os.listdir(self.dz+"\\tmp"):
            if music[-3:]!='lrc':
                musics.append(music)
        if not(name in musics):
            print("默认下载第一首\n准备下载")
            print("文件名 "+name)
            print("保存在 "+self.dz+"\\tmp")
            # print(link)
            downlad=requests.get(link)
            fm=requests.get(fmlink)
            with open(self.dz+"\\tmp\\"+name,"wb") as file:
                file.write(downlad.content)
            with open(self.dz+"\\tmp\\"+name+".jpg","wb") as file:
                file.write(fm.content)
            # try:
            #     print("尝试设置封面")
            #     mus=eyed3.load(path=self.dz+"\\tmp\\"+name)
            #     mus.tag.images.set(ImageFrame.FRONT_COVER, open(self.dz+"\\tmp\\"+name+".jpg", 'rb').read(), 'image/jpg')
            #     mus.tag.save(version=eyed3.id3.ID3_DEFAULT_VERSION, encoding='utf-8')
            #     print("设置封面成功")
            # except BaseException as e:
            #     print("设置封面失败 :\n",e)
            with open(self.dz+"\\tmp\\"+name+".lrc","w") as file:
                file.write("[ti:"+title+"]\n")
                file.write("[ar:"+people+"]\n")
                file.write(convertTostring(links.split(",")[1]))
            try:
                ttmp=self.mp3_bit(self.dz+"\\tmp\\"+name)
                print("比特率:"+str(ttmp[0])+"kbps 时长:"+str(int(ttmp[1]//60))+"分"+str(round(ttmp[1]%60))+"秒")
            except:
                # os.remove(self.dz+"\\tmp\\"+name)
                # input("检测到歌曲无法播放，已删除")
                # return
                print("读取文件信息失败")
            print("下载完成")
        else:
            print("检测到第一首已经下载过了")
        tt=input("打开(y/n)?")
        if not tt=="n":
            os.system("python .\\lib\\player_gui.py "+self.dz+"\\tmp\\"+name)